package ACM_Brush;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;

public class Solution042 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] array = new int[n];

        for (int i = 0; i < n; i++) {
            array[i] = in.nextInt();
        }

        in.close();

        System.out.println(new question().getRain2(array));
    }
}

class question {
    public int getRain(int[] array) {
        int length = array.length;
        int[] leftMax = new int[length];
        int[] rightMax = new int[length];

        leftMax[0] = 0;
        rightMax[length - 1] = 0;
        for (int i = 1; i < length; i++) {
            leftMax[i] = Math.max(array[i - 1], leftMax[i - 1]);
        }

        for (int i = length - 2; i >= 0; i--) {
            rightMax[i] = Math.max(array[i + 1], rightMax[i + 1]);
        }

        int sum = 0;

        for (int i = 1; i < length - 1; i++) {
            if (Math.min(leftMax[i], rightMax[i]) > array[i])
                sum += Math.min(leftMax[i], rightMax[i]) - array[i];
        }

        return sum;
    }

    public int getRain2(int[] array) {
        int result = 0;
        Deque<Integer> stack = new LinkedList<>();
        for (int i = 0; i < array.length; i++) {
            while (!stack.isEmpty() && array[i] > array[stack.peek()]) {
                int top = stack.pop();
                if (stack.isEmpty())
                    break;
                int left = stack.peek();
                int width = i - left - 1; // 计算宽度
                result += (Math.min(array[left], array[i]) - array[top]) * width;
            }
            stack.push(i);
        }

        return result;
    }
}